define(function(require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    require('./privateMsgNewCtrl');
    require('./privateMsgDetailCtrl');
    

    $.widget('rk.privateMsgCtrl', {
            _recentPageNo: 0,
            _contactPageNo: 0,
            _groupPageNo: 0,
            _recentDataLoading: false,
            _contactDataLoading: false,
            _groupDataLoading: false,
            _create: function(){
                var me = this;
                var elem = me.element;

                me._initControl();
            },
            _init: function(){
                var me = this;
                var elem = me.element;

               
                elem.find('#pm-list').beScroll({
                    whileScrolling:function(){
                        var con = elem.find('.mCSB_draggerContainer');
                        var rel_con = elem.find('.mCSB_container');

                        if(Math.abs(rel_con.css('top').slice(0,-2)) > rel_con.height() - 375){
                            if(elem.find('.message-tab').hasClass('hidden') === false){
                                me._getData();
                            }
                            if(elem.find('.group-tab').hasClass('hidden') === false){
                                me._getGroupData();
                            }
                            if(elem.find('.person-tab').hasClass('hidden') === false){
                                me._getPersonData();
                            }
                        }
                    }
                });

                //me.initUnRead();
                //me._getData();
                //me._getGroupData();
                //me._getPersonData(); 
            },
            _initControl: function() {
                var me = this;
                var elem = me.element;

                elem.find('.pg-pm-thumb').on('click',function(evt){
                    elem.find('.pg-pm-thumb').hide();
                    elem.find('.pg-pm-content').slideDown(200);
                    if(elem.find('.message-tab').find('li').length === 0){
                        me._getData();
                    }
                    elem.find('.message-tab').removeClass('hidden');
                    elem.find('.person-tab').addClass('hidden');
                    elem.find('.group-tab').addClass('hidden');
                    elem.find('.pm-nav-list > li').find('a > i.message').parent().addClass('active');
                    elem.find('.pm-nav-list > li').find('a > i.person').parent().removeClass('active');
                    elem.find('.pm-nav-list > li').find('a > i.group').parent().removeClass('active');
                }).beTip({dir:'left'});

                elem.find('.pg-pm-close').on('click',function(){
                    elem.find('.pg-pm-messagebox').hide();
                    elem.find('.pm_detail').hide();
                    elem.find('.pg-pm-gset').hide();
                    try {
                        elem.find('.pg-pm-messagebox').privateMsgDetailCtrl("destroy");
                    } catch (e) {}
                    try {
                        elem.find('.pm_detail').privateMsgNewCtrl("destroy");
                    } catch (e) {}

                    elem.find('.pg-pm-content').slideUp(200,function(){
                        elem.find('.pg-pm-thumb').show();
                    });
                });

                elem.find('.pm-nav-list > li').each(function(){
                    var btn = $(this);
                    btn.on('click',function(){
                        var target = $(this);
                        elem.find('.pm-nav-list > li').each(function(){
                            var ebtn = $(this);
                            if(ebtn.find('a > i')[0].className === target.find('a > i')[0].className){
                                target.find('a').addClass('active');
                            }else{
                                ebtn.find('a').removeClass('active');
                            }
                        });

                        switch(target.find('a > i')[0].className){
                            case "message":
                                elem.find('.message-tab').removeClass('hidden');
                                elem.find('.person-tab').addClass('hidden');
                                elem.find('.group-tab').addClass('hidden');
                                break;
                            case "person":
                                elem.find('.message-tab').addClass('hidden');
                                elem.find('.person-tab').removeClass('hidden');
                                elem.find('.group-tab').addClass('hidden');
                                if(elem.find('.person-tab').html() === ''){
                                    me._getPersonData();
                                }
                                break;
                            case "group":
                                elem.find('.message-tab').addClass('hidden');
                                elem.find('.person-tab').addClass('hidden');
                                elem.find('.group-tab').removeClass('hidden');
                                if(elem.find('.group-tab').html() === ''){
                                    me._getGroupData();
                                }
                                break;
                        }
                    });
                });

                elem.find('.add-chat').click(function(){
                    elem.find('.pg-pm-messagebox').hide();
                    elem.find('.pm_detail').hide();
                    elem.find('.pg-pm-gset').hide();
                    try {
                        elem.find('.pg-pm-messagebox').privateMsgDetailCtrl("destroy");
                    } catch (e) {}

                    try {
                        elem.find('.pm_detail').privateMsgNewCtrl("destroy");
                    } catch (e) {}

                    elem.find('.pm_detail').privateMsgNewCtrl();
                });

                elem.on('click','ul.pm-people-list > li' , function(){
                    var target = $(this);

                    elem.find('ul.pm-people-list > li').each(function(){
                        $(this).removeClass('hover');
                    });
                    target.addClass('hover');

                    if(target.attr('targetId') === undefined){
                        try {
                            elem.find('.pm_detail').privateMsgNewCtrl("destroy");
                        } catch (e) {}

                        var pmId = null,
                            clickPmId = target.attr("pm-id"),
                            isGroup = target.attr("pm-type"),
                            isDead = target.attr("pm-is-dead");
                        try {
                            pmId = elem.find('.pg-pm-messagebox').privateMsgDetailCtrl("currentId");
                        } catch (e) {
                            pmId = null;
                        }
                        if (pmId != clickPmId) {
                            elem.find('.pg-pm-messagebox').privateMsgDetailCtrl({
                                privateMsgId: clickPmId,
                                pageNo: 1,
                                pageSize: 20,
                                isGroup: isGroup,
                                groupDead: isDead
                            });
                            //清除上面的未读提示数字,更新总提示
                            var unread = target.find("span.news");
                            if(unread !== undefined){
                                var oldNum = window.SESSION.privateMsgUnRead;
                                var newNum = unread.text();
                                if(oldNum - newNum > 0){
                                    window.SESSION.privateMsgUnRead = oldNum - newNum;
                                    if(oldNum - newNum > 99){
                                        elem.find('.pg-pm-thumb > span.num').text('99+');
                                    }else{
                                        elem.find('.pg-pm-thumb > span.num').text(oldNum - newNum);
                                    }
                                }else{
                                    window.SESSION.privateMsgUnRead = 0;
                                    elem.find('.pg-pm-thumb > span.num').text('');
                                    elem.find('.pg-pm-thumb > span.num').hide();
                                }
                                unread.remove();
                            }
                        }
                    }else{
                        me.openMsg(target.attr('targetId'),target.attr('targetName'),target.find('img').attr('src'));
                    }
                });

                var searchTimeout = null;
                elem.find('.search-text').on('focusin',function(){
                    if(elem.find('.pg-pm-search').hasClass('active') === false){ 
                       elem.find('.pg-pm-search').addClass('active');
                       elem.find('.pg-pm-search > .cancel').show();
                       me.initSearch();
                    }
                }).on('keyup',function(){
                    var searchKey = $(this);
                    clearTimeout(searchTimeout);
                    if(searchKey.val().length > 0){
                        searchTimeout = setTimeout(function(){
                            me.renderSearch();
                        },500);
                    }
                });

                elem.find('.pg-pm-search').find('a.cancel').click(function(){
                   try{
                       elem.find('.pg-pm-search').removeClass('active');
                       elem.find('.pg-pm-container').find('.pg-pm-searchtab').remove();
                       elem.find('.pg-pm-nav').show();
                       elem.find('#pm-list').show();
                       elem.find('.pg-pm-searchtab').hide();
                       elem.find('input.search-text').val('');
                   }catch(e){}
                });

                elem.find('.pg-pm-search').find('a.search-btn').on('click',function(){
                   me.renderSearch();
                });

                elem.find('.pg-pm-search').find('.search-text').on('keydown',function(evt){
                   if(evt.keyCode === 13){
                        elem.find('.pg-pm-search').find('a.search-btn').trigger('click');
                    }
                });

               $('#privaemsg').data('msgInited','privatemsginited');
            },
            initUnRead: function(){
                var me = this;
                var elem = me.element;

                $.getJSON('/json/sns_wx/unread-count.action').done(function(json) {
                    if(json.status){
                        return;
                    }
                    if(json.data > 0){
                        var unReadCount = json.data;
                        if(json.data > 99){
                            unReadCount = '99+';
                        }
                        elem.find('.pg-pm-thumb > span.num').text(unReadCount);
                        elem.find('.pg-pm-thumb > span.num').show();

                        window.SESSION.privateMsgUnRead = json.data;
                    }
                });
            },
            _getData: function(){
                var me = this;
                var elem = me.element;

                if(me._recentDataLoading){
                    return;
                }

                me._recentPageNo += 1;

                if(elem.find('.message-tab').find('ul.pm-people-list').length === 0){
                    elem.find('.message-tab').append('<div class="loading"></div>');
                    elem.find('.message-tab').find('.loading').beLoading({delay:0});
                }

                me._recentDataLoading = true;
                $.postJson('/json/sns_wx/list.action',{
                    pageNo: me._recentPageNo,
                    pageSize: 20
                }).done(function(json) {
                    elem.find('.message-tab').find('.loading').remove();
                    if (json.status) {
                        me._recentDataLoading = false;
                        rk.noticeError(json.status);
                        return;
                    }
                    if (json.data && elem.find('.message-tab').hasClass('hidden') === false) {
                        if(json.data.privatemsgs.length > 0){
                            me._recentDataLoading = false;
                            elem.find('.pg-pm-black').remove();
                            if(elem.find('.message-tab').find('ul.pm-people-list').length === 0){
                                elem.find('.message-tab').append('<div class="pm-people-box recent-contacts-box"><ul class="pm-people-list">');
                            }

                            for(var i=0; i< json.data.privatemsgs.length; i++){
                                var eachData = json.data.privatemsgs[i];
                                var liEle = null;
                                if(eachData.type == 0){
                                    liEle = me._appendSingleDialog(eachData);
                                }else{
                                    liEle = me._appendGroupDialog(eachData);
                                }
                                elem.find('.message-tab > .recent-contacts-box > .pm-people-list').append(liEle);  
                            }
                            if(json.data.privatemsgs.length > 6){
                                elem.find('.message-tab').append('<div class="loading"></div>');
                                elem.find('.message-tab').find('.loading').beLoading();
                            }
                        }else{
                            elem.find('.pg-pm-black').show();
                        }
                    }
                }).fail(function(def, code, message) {}); 
            },
            _getGroupData: function(){
                var me = this;
                var elem = me.element;

                if(me._groupDataLoading){
                    return;
                }

                me._groupPageNo += 1;

                if(elem.find('.group-tab').find('ul.pm-people-list').length === 0){
                    elem.find('.group-tab').append('<div class="loading"></div>');
                    elem.find('.group-tab').find('.loading').beLoading({delay:0});
                }
                
                me._groupDataLoading = true;
                $.getJSON("/json/sns_wx/groups.action", {
                    pageNo: me._groupPageNo,
                    pageSize: 20
                }).done(function(json) {
                    elem.find('.group-tab').find('.loading').remove();
                    if (json.status) {
                        me._groupDataLoading = false;
                        rk.noticeError(json.status);
                        return;
                    }
                    if(elem.find('.group-tab').hasClass('hidden')){
                        return;
                    }
                    if(json.data.privatemsgs && json.data.privatemsgs.length > 0){
                        
                        me._groupDataLoading = false;
                        if(elem.find('.group-tab').find('ul.pm-people-list').length === 0){
                            elem.find('.group-tab').append('<div class="pm-people-box group-contacts-box"><ul class="pm-people-list">');
                        }

                        for(var i=0; i< json.data.privatemsgs.length; i++){
                            var eachData = json.data.privatemsgs[i];
                            var groupLi = me._appendMyGroup(eachData);

                            elem.find('.group-tab > .group-contacts-box > .pm-people-list').append(groupLi);
                        }
                        if(json.data.privatemsgs.length > 6){
                            elem.find('.group-tab').append('<div class="loading"></div>');
                            elem.find('.group-tab').find('.loading').beLoading();
                        }
                    }
                }).fail(function(def, code, message) {});    
            },
            _getPersonData: function(){
                var me = this;
                var elem = me.element;

                if(me._contactDataLoading){
                    return;
                }

                me._contactPageNo += 1;

                if(elem.find('.person-tab').find('ul.pm-people-list').length === 0){
                    elem.find('.person-tab').append('<div class="loading"></div>');
                    elem.find('.person-tab').find('.loading').beLoading({delay:0});
                }


                me._contactDataLoading = true;

                $.postJson("/json/oa_colleague/colleague-query-list.action", {
                    pageNo: me._contactPageNo,
                    pageSize: 20
                    //colleagueName:
                }).done(function(json) {
                    elem.find('.person-tab').find('.loading').remove();
                    if (json.status) {
                        me._contactDataLoading = false;
                        rk.noticeError(json.status);
                        return;
                    }
                    if(elem.find('.person-tab').hasClass('hidden')){
                        return;
                    }
                    if(json.colleagues.length > 0){
                        me._contactDataLoading = false;
                        if(elem.find('.person-tab').find('ul.pm-people-list').length === 0){
                            elem.find('.person-tab').append('<div class="pm-people-box company-book-box"><ul class="pm-people-list">');
                        }

                        for(var i=0; i< json.colleagues.length; i++){
                            var eachData = json.colleagues[i];
                            if(eachData.userId !== SESSION.user.id){
                                me._appendPerson(eachData);
                            }
                        }
                        if(json.colleagues.length > 6){
                            elem.find('.person-tab').append('<div class="loading"></div>');
                            elem.find('.person-tab').find('.loading').beLoading();
                        }
                    }
                }).fail(function(def, code, message) {});
            },
            _appendSingleDialog: function(data){
                var me = this;
                var elem = me.element;

                var addData = {};
                addData.targetUserId = data.targetUserId;
                addData.targetUsername = data.targetUser.name;
                addData.targetUserIcon = data.targetUser.icon || DEFAULTS.USER_DEFAULT_ICON;
                addData.unReadCount = data.unreadCount;
                addData.latestContent = data.latestContent;
                addData.latestContentTime = me._parseDate(new Date(data.latestContentTime));
                addData.pmId = data.id;
                addData.pmType = data.type;

                var singleDialogLiTpl = require('page/tmpl/privatemsg/singleDialogLi.tpl');
                var singleDialogHtml = rk.templateText(singleDialogLiTpl,addData);

                return $(singleDialogHtml);
            },
            _appendGroupDialog: function(data){
                var me = this;
                var elem = me.element;

                var groupName = data.title;
                var avatarIcons = '';
                var hasName = groupName === ''?false:true;
                
                for(var i=0; i<data.memberIdList.length; i++){
                    var mid = data.memberIdList[i];
                    if(!hasName){
                        if(i < 6){   
                            groupName += mid.name;
                        }
                        if(i < data.memberIdList.length - 1 && i < 5){
                            groupName += '、';
                        }
                        if(data.memberIdList.length > 5 && i == 5){
                            groupName += rk.i18n('PRIVATEMSG_AND_SO_ON',data.memberIdList.length);
                        }
                    }
                    if (i < 10) {
                        if (mid.id != SESSION.user.id) {
                            avatarIcons += '<img src="' + (mid.icon || DEFAULTS.USER_DEFAULT_ICON) + '"/>';
                        }
                    }
                }

                var addData = {};
                addData.groupName = groupName;
                addData.unReadCount = data.unreadCount;
                addData.latestContent = data.latestContent;
                addData.latestContentTime = me._parseDate(new Date(data.latestContentTime));
                addData.avatarIcons = avatarIcons;
                addData.pmId = data.id;
                addData.pmType = data.type;
                addData.dead = data.dead;

                var groupDialogLiTpl = require('page/tmpl/privatemsg/groupDialogLi.tpl');
                var groupDialogHtml = rk.templateText(groupDialogLiTpl,addData); 

                return $(groupDialogHtml); 
            },
            _appendMyGroup: function(data){
                var me = this;
                var elem = me.element;

                var groupName = data.title;
                var avatarIcons = '';
                var hasName = groupName === ''?false:true;
                for(var i=0; i<data.memberIdList.length; i++){
                    var mid = data.memberIdList[i];
                    if(!hasName){
                        if(i < 6){   
                            groupName += mid.name;
                        }
                        if(i < data.memberIdList.length - 1 && i < 5){
                            groupName += '、';
                        }
                        if(data.memberIdList.length > 5 && i == 5){
                            groupName += rk.i18n('PRIVATEMSG_AND_SO_ON',data.memberIdList.length);
                        }
                    }
                    if (i < 10) {
                        if (mid.id != SESSION.user.id) {
                            avatarIcons += '<img src="' + (mid.icon || DEFAULTS.USER_DEFAULT_ICON) + '"/>';
                        }
                    }
                }

                var addData = {};
                addData.groupName = groupName;
                addData.memberCount = data.memberIdList.length;
                addData.avatarIcons = avatarIcons;
                addData.pmId = data.id;
                addData.pmType = data.type;

                var groupDialogLiTpl = require('page/tmpl/privatemsg/groupListLi.tpl');
                var groupDialogHtml = rk.templateText(groupDialogLiTpl,addData);

                return $(groupDialogHtml);
            },
            _appendPerson: function(data){
                var me = this;
                var elem = me.element;

                var addData = {};
                addData.userId = data.userId;
                addData.userIcon = data.smallIcon || window.DEFAULTS.USER_DEFAULT_ICON;
                addData.userName = data.userName;
                addData.departName = data.departName;
                addData.positionName = data.positionName;

                var groupDialogLiTpl = require('page/tmpl/privatemsg/personLi.tpl');
                var groupDialogHtml = rk.templateText(groupDialogLiTpl,addData);

                elem.find('.person-tab > .company-book-box > .pm-people-list').append(groupDialogHtml);
            },
            showMsg: function(){
                var me = this;
                var elem = me.element;
                if(!elem.find('.pg-pm-content').is(':visible')){
                    elem.find('.pg-pm-thumb').hide();
                    elem.find('.pg-pm-content').show();
                    elem.find('.message-tab').removeClass('hidden');
                    if(elem.find('.message-tab').find('li').length === 0){
                        me._getData();
                    }
                }
            },
            openMsg: function(targetId,targetName,targetIcon){
                var me = this;
                var elem = me.element;

                $.postJson('/json/sns_wx/detail.action',{
                    targetUserId: targetId
                }).done(function(json){
                    if(json.status){
                        rk.noticeError(json.status);
                        return false;
                    }

                    if(!elem.find('.pg-pm-content').is(':visible')){
                        elem.find('.pg-pm-thumb').hide();
                        elem.find('.pg-pm-content').show();
                        if(elem.find('.message-tab').find('li').length === 0){
                            me._getData();
                        }
                    }
                    elem.find('.message-tab').removeClass('hidden');
                    elem.find('.pg-pm-messagebox').hide();
                    elem.find('.pm_detail').hide();
                    elem.find('.pg-pm-gset').hide();

                    try {
                        elem.find('.pg-pm-messagebox').privateMsgDetailCtrl("destroy");
                    } catch (e) {}

                    try {
                        elem.find('.pm_detail').privateMsgNewCtrl("destroy");
                    } catch (e) {}
                    console.log(json.data);
                    if(json.data.pmId && json.data.pmId !== ''){
                        elem.find('.pg-pm-messagebox').privateMsgDetailCtrl({
                            privateMsgId: json.data.pmId,
                            pageNo: 1,
                            pageSize: 20,
                            isGroup: json.data.pmType,
                            groupDead: json.data.dead
                        });
                    }else{
                        var orderTarget = {};
                        orderTarget.key = targetId;
                        orderTarget.value = targetName;
                        if(targetIcon){
                            orderTarget.icon = targetIcon;
                        }else{
                            orderTarget.icon = window.DEFAULTS.USER_DEFAULT_ICON;
                        }
                        elem.find('.pm_detail').privateMsgNewCtrl({
                            orderTarget:orderTarget
                        });
                    }
                    elem.find('.message_sent_li').find('textarea').focus();
                }).fail(function(def, code, message) {}); 
            },
            /**
             * 重新排序私信列表
             * @param topId 是要被重置到最顶端的私信
             * @param addBadgeCount 如果有，需要在这条私信上新加上addBadgeCount数量的badge，注意，是在原有的badge数基础上叠加上
             */
            reorderList: function(topId, addBadgeCount,groupNewName,op) {
                var me = this;
                var elem = me.element;
                var opt = me.options;

                $.getJSON("/json/sns_wx/get-chat.action", {
                    privateMsgId: topId
                }).done(function(json) {
                    if (json.status) {
                        rk.noticeError(json.status);
                        return;
                    }
                    if (json.data) {
                        var eachData = null;
                        var hasLi = false;
                        var liEle = null;

                        /*if(elem.find('.pg-pm-black') !== undefined){
                            elem.find('.pg-pm-black').remove();
                            elem.find('.message-tab').append('<div class="pm-people-box recent-contacts-box"><ul class="pm-people-list">');
                        }*/

                        for(var i=0; i< json.data.privatemsgs.length; i++){
                            eachData = json.data.privatemsgs[i];
                        }


                        elem.find('.message-tab > .recent-contacts-box > .pm-people-list > li').each(function(i, o) {
                            var target = $(o);
                            if (target.attr("pm-id") == topId) {
                                //直接将o放在最上方
                                hasLi = true;
                                if(groupNewName){
                                    target.find('div.show-info > a.name').text(groupNewName);
                                }
                                target.find('div.show-info > p.msgex').text(eachData.latestContent);
                                target.find('div.daily-tool').text(me._parseDate(new Date(eachData.latestContentTime)));
                                target.prependTo(target.parent());
                                liEle = target;
                                return false;
                            }
                        });

                        if(!hasLi && !me._recentDataLoading){
                            if(eachData.type == 0){
                                liEle = me._appendSingleDialog(eachData);
                            }else{
                                liEle = me._appendGroupDialog(eachData);

                                if(elem.find('.group-tab').find('li').length === 0){
                                    me._getGroupData();
                                }else{
                                    var groupLiEle = me._appendMyGroup(eachData);
                                    groupLiEle.prependTo(elem.find(".group-tab > .group-contacts-box > .pm-people-list"));
                                }
                            }

                            liEle.prependTo(elem.find(".message-tab > .recent-contacts-box > .pm-people-list"));

                            //对话hover
                            if(op && op === 'tophover'){
                                elem.find('.message-tab > .recent-contacts-box > .pm-people-list > li').each(function(){
                                    $(this).removeClass('hover');
                                });
                                elem.find('.message-tab > .recent-contacts-box > .pm-people-list').find('li[pm-id="'+topId+'"]').addClass('hover');
                            }
                        }

                        //新建对话打开
                        if(op && op === 'open'){
                            elem.find(".message-tab > .recent-contacts-box > .pm-people-list").find('li[pm-id="'+eachData.id+'"]').trigger('click');
                        }

                        if (addBadgeCount && liEle != null) {
                            var oldBadge = liEle.find("span.news");
                            if (oldBadge.length > 0) {
                                if (oldBadge.text() != "99+") {
                                    oldBadge.text(parseInt(oldBadge.text()) + parseInt(addBadgeCount));
                                }
                            } else {
                                var badgeHtml = '<span class="news">' + addBadgeCount + '</span>';
                                liEle.find("div.show-content > a").append($(badgeHtml));
                            }
                        }

                        elem.find('#pm-list').beScrollTo('top');
                    }
                }).fail(function(def, code, message) {});
            },
            resetGroupList: function(topId,groupNewName){
                var me = this;
                var elem = me.element;
                var opt = me.options;
                elem.find('.group-tab > .group-contacts-box > .pm-people-list > li').each(function(i, o) {
                    var target = $(o);
                    if (target.attr("pm-id") == topId) {
                        if(groupNewName){
                            target.find('div.show-info > p.groups > span.group-name').text(groupNewName);
                        }
                        return false;
                    }
                });
            },
            removeList: function(removeId){
                var me = this;
                var elem = me.element;
                var opt = me.options;
                elem.find('.message-tab > .recent-contacts-box > .pm-people-list > li').each(function(i, o) {
                    var target = $(o);
                    if (target.attr("pm-id") == removeId) {
                        target.remove();
                        return false;
                    }
                });

                elem.find('.group-tab > .group-contacts-box > .pm-people-list > li').each(function(i, o) {
                    var target = $(o);
                    if (target.attr("pm-id") == removeId) {
                        target.remove();
                        return false;
                    }
                });

                if(elem.find('.message-tab > .recent-contacts-box > .pm-people-list > li').length < 6){
                    me._getData();
                }
            },
            initSearch: function(){
                var me = this;
                var elem = me.element;

                elem.find('.pg-pm-nav').hide();
                elem.find('#pm-list').hide();

                elem.find('.pg-pm-container').find('.pg-pm-searchtab').remove();
                elem.find('.pg-pm-container').append('<div class="pg-pm-tab pg-pm-searchtab"></div>');

                $.postJson('/json/sns_wx/recent-contacts.action',{
                    pageNo: 1,
                    pageSize: 10
                }).done(function(json) {
                    if (json.status) {
                        rk.noticeError(json.status);
                        return;
                    }
                    if (json.data) {
                        var recentList = json.data.recentContacts;

                        if(recentList.length > 0){
                            var historyTpl = require('page/tmpl/privatemsg/privateMsgSearchHistory.tpl');
                            var historyHtml = rk.templateText(historyTpl,{list:recentList});
                            elem.find('.pg-pm-container >.pg-pm-searchtab').append(historyHtml); 

                            /*elem.find('.pg-pm-container >.pg-pm-searchtab').find('.recently-search-list>li').on('click',function(){
                                var target = $(this);
                                me.openMsg(target.attr('targetId'),target.attr('targetName'));
                            });*/
                            elem.find('.pg-pm-container >.pg-pm-searchtab').beScroll();
                        }else{
                            elem.find('.pg-pm-container >.pg-pm-searchtab').append('<div class="message-tab"><div class="pg-pm-black"><span class="pm-no-history">'+rk.i18n('PRIVATEMSG_QUERY_COLLEAGUE_GROUP_NAME')+'</span></div></div>');
                        }     
                    }
                }).fail(function(def, code, message) {});
            },
            renderSearch: function(){
                var me = this;
                var elem = me.element;

                var searchKey = $('input.search-text').val();
                if(searchKey === ''){
                    return;
                }
                
                elem.find('.pg-pm-container').find('.pg-pm-searchtab').remove();
                elem.find('.pg-pm-container').append('<div class="pg-pm-tab pg-pm-searchtab"></div>');

                elem.find('.pg-pm-searchtab').append('<div class="loading"></div>');
                elem.find('.pg-pm-searchtab').find('.loading').beLoading({delay:0});

                var personSearchList = null;
                $.postJson("/json/oa_colleague/colleague-query-list.action", {
                    pageNo: 1,
                    pageSize: 3,
                    colleagueName: searchKey
                }).done(function(json) {
                    if (json.status) {
                        rk.noticeError(json.status);
                        return;
                    }
                    if(json.colleagues.length > 0){
                        personSearchList = json.colleagues;
                    }else{
                        personSearchList = [];
                    }
                    me.renderSearchGroup(personSearchList);
                }).fail(function(def, code, message) {});
            },
            renderSearchGroup: function(personSearchList){
                var me = this;
                var elem = me.element;

                var personList = personSearchList;
                var groupList = [];

                var searchKey = $('input.search-text').val();

                $.getJSON("/json/sns_wx/search-groups.action", {
                    key: searchKey
                }).done(function(json) {
                    elem.find('.pg-pm-searchtab').find('.loading').remove();
                    if (json.status) {
                        rk.noticeError(json.status);
                        return;
                    }
                    if(elem.find('.pg-pm-container').find('.pg-pm-searchtab').size()==0 || !elem.find('.pg-pm-container').find('.pg-pm-searchtab').is(':visible')){
                        return;
                    }
                    if(json.data.privatemsgs.length > 0){
                        for(var i=0;i<json.data.privatemsgs.length;i++){
                            if(i<3){
                                var data = json.data.privatemsgs[i];
                                var groupName = data.title;
                                if(groupName === ''){
                                    for(var j=0; j<data.memberIdList.length; j++){
                                        var mid = data.memberIdList[j];
                                        if(j < 6){   
                                            groupName += mid.name;
                                        }
                                        if(j < data.memberIdList.length - 1 && j < 5){
                                            groupName += '、';
                                        }
                                        if(data.memberIdList.length > 5 && j == 5){
                                            groupName += rk.i18n('PRIVATEMSG_AND_SO_ON',data.memberIdList.length);
                                        }
                                    }
                                }
                                data.title = groupName;
                                groupList.push(data);
                            }else{
                                break;
                            }
                        }
                    }

                    elem.find('.pg-pm-container').find('.pg-pm-searchtab').remove();
                    elem.find('.pg-pm-container').append('<div class="pg-pm-tab pg-pm-searchtab"></div>');

                    if(groupList.length === 0 && personList.length === 0){
                        elem.find('.pg-pm-container >.pg-pm-searchtab').append('<div class="message-tab"><div class="pg-pm-black pg-pm-searchblack"><span class="pm-no-search">'+rk.i18n('PRIVATEMSG_NO_SEARCH')+' “'+searchKey+'” '+rk.i18n('PRIVATEMSG_NO_SEARCH_PEOPLE')+'</span></div></div>');                    
                    }else{
                        var searchResultTpl = require('page/tmpl/privatemsg/privateMsgSearchResult.tpl');

                        var searchResultData = {};
                        if(personList.length !== 0){
                            searchResultData.personList = personList;
                        }
                        if(groupList.length !== 0){
                            searchResultData.groupList = groupList;
                        }
                        searchResultData.type = 'all';

                        var searchResultHtml = rk.templateText(searchResultTpl,searchResultData);
                        elem.find('.pg-pm-container >.pg-pm-searchtab').append(searchResultHtml);

                        elem.find('.pg-pm-container >.pg-pm-searchtab >.search-result-box > .search-contacts-box > span.title >  a.more').click(function(){
                                me.searchPerson();
                        });

                        elem.find('.pg-pm-container >.pg-pm-searchtab >.search-result-box > .search-group-box > span.title > a.more').click(function(){
                                me.searchGroup();
                        });
                    }
                }).fail(function(def, code, message) {});
            },
            searchPerson: function(){
                var me = this;
                var elem = me.element;

                var searchKey = $('input.search-text').val();

                $.postJson("/json/oa_colleague/colleague-query-list.action", {
                    pageNo: 1,
                    pageSize: 20,
                    colleagueName: searchKey
                }).done(function(json) {
                    if (json.status) {
                        rk.noticeError(json.status);
                        return;
                    }
                    if(elem.find('.pg-pm-container').find('.pg-pm-searchtab').size()==0 || !elem.find('.pg-pm-container').find('.pg-pm-searchtab').is(':visible')){
                        return;
                    }
                    if(json.colleagues.length > 0){
                        elem.find('.pg-pm-container').find('.pg-pm-searchtab').remove();
                        elem.find('.pg-pm-container').append('<div class="pg-pm-tab pg-pm-searchtab"></div>');

                        var searchResultTpl = require('page/tmpl/privatemsg/privateMsgSearchResult.tpl');
                        var searchResultData = {};
                        searchResultData.personList = json.colleagues;
                        searchResultData.type = rk.i18n('PRIVATEMSG_COLLEAGUE');
                        var searchResultHtml = rk.templateText(searchResultTpl,searchResultData);
                        elem.find('.pg-pm-container >.pg-pm-searchtab').append(searchResultHtml);
                        elem.find('.pg-pm-container >.pg-pm-searchtab').find('.search-result-box').beScroll();
                        elem.find('.pg-pm-container >.pg-pm-searchtab').find('.search-crumbs > span.first > a').click(function(){
                            me.renderSearch();
                        });
                    }
                }).fail(function(def, code, message) {});
            },
            searchGroup: function(){
                var me = this;
                var elem = me.element;

                var searchKey = $('input.search-text').val();

                $.getJSON("/json/sns_wx/search-groups.action", {
                    key: searchKey,
                    searchMore: true
                }).done(function(json) {
                    if (json.status) {
                        rk.noticeError(json.status);
                        return;
                    }
                    if(elem.find('.pg-pm-container').find('.pg-pm-searchtab').size()==0 || !elem.find('.pg-pm-container').find('.pg-pm-searchtab').is(':visible')){
                        return;
                    }
                    if(json.data.privatemsgs.length > 0){
                        elem.find('.pg-pm-container').find('.pg-pm-searchtab').remove();
                        elem.find('.pg-pm-container').append('<div class="pg-pm-tab pg-pm-searchtab"></div>');

                        var searchResultTpl = require('page/tmpl/privatemsg/privateMsgSearchResult.tpl');
                        var searchResultData = {};
                        var groupList = [];
                        for(var i=0;i<json.data.privatemsgs.length;i++){
                            var data = json.data.privatemsgs[i];
                            var groupName = data.title;
                            if(groupName === ''){
                                for(var j=0; j<data.memberIdList.length; j++){
                                    var mid = data.memberIdList[j];
                                    if(j < 6){   
                                        groupName += mid.name;
                                    }
                                    if(j < data.memberIdList.length - 1 && j < 5){
                                        groupName += '、';
                                    }
                                    if(data.memberIdList.length > 5 && j == 5){
                                        groupName += rk.i18n('PRIVATEMSG_AND_SO_ON',data.memberIdList.length);
                                    }
                                }
                            }
                            data.title = groupName;

                            groupList.push(data);
                        }

                        searchResultData.groupList = groupList;
                        searchResultData.type = rk.i18n('PRIVATEMSG_GROUP_TALK');
                        var searchResultHtml = rk.templateText(searchResultTpl,searchResultData);
                        elem.find('.pg-pm-container >.pg-pm-searchtab').append(searchResultHtml);
                        elem.find('.pg-pm-container >.pg-pm-searchtab').find('.search-result-box').beScroll();
                        elem.find('.pg-pm-container >.pg-pm-searchtab').find('.search-crumbs > span.first >  a').click(function(){
                            me.renderSearch();
                        });
                    }
                }).fail(function(def, code, message) {});
            },
            onOAResize: function(type){
                var me = this;
                var elem = me.element;

                if(type === 'oashow'){
                    elem.css('right','401px');
                    elem.find('.pg-pm-content').css('right','0px');
                    elem.find('.pg-pm-gset').css('right','250px');
                    elem.find('.pg-pm-messagebox').css('right','249px');
                    elem.find('.pm_detail').css('right','250px');
                }else if(type === 'oahide'){
                    elem.css('right','0px');
                    elem.find('.pg-pm-content').css('right','20px');
                    elem.find('.pg-pm-gset').css('right','270px');
                    elem.find('.pg-pm-messagebox').css('right','269px');
                    elem.find('.pm_detail').css('right','270px');
                }
            },
            toMin: function(){
                var me = this;
                var elem = me.element;

                elem.find('.pg-pm-close').trigger('click');
            },
            _parseDate: function(date) {
                var ct = new Date();
                var dateString = '';

                if(Globalize.format(date,rk.i18n('PRIVATEMSG_FORMAT_DATE_YEAR_MONTH_DAY')) === Globalize.format(ct,rk.i18n('PRIVATEMSG_FORMAT_DATE_YEAR_MONTH_DAY'))){
                    dateString = Globalize.format(date,'HH:mm');
                }else{
                    dateString = Globalize.format(date,'M-d');
                }
                return dateString;
            },
    });

    return $;
});